<?php

namespace app\api\controller;

use app\helps\Mns;
use app\facade\Redis;
use app\models\{HallTrade, Hall as Halls, User, HallTradeAppeal, UserAuth, Config, Payment, UserConfig, Price};
use think\Db;
use think\Validate;

class Hall extends Base
{
    //场外交易列表
    public function lists()
    {
        $result = (new Halls())->where('type', 2)
            ->where('user_id', '<>', $this->request->user_id)
            ->where('status', 0)
            ->field('id,num,user_id,price,payment')
            ->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['level'] = (new User())->where('id', $results['user_id'])->value('level');
            $results['payment'] = json_decode($results['payment'], true);
        }
        $this->result($result, 0, '获取成功');
    }

    //发布场外交易
    public function input()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'trade' => 'require',
                'num' => 'require|float|gt:0',
                'price' => 'require|float|gt:0',
                'payment' => 'require',
            ], [
                'num.require' => '请输入交易数量',
                'num.float' => '交易数量必须是数字',
                'num.gt' => '交易数量必须大于0',
                'trade.require' => '请输入交易密码',
                'price.require' => '请输入交易价格',
                'price.gt' => '交易价格必须是数字',
                'price.gt' => '交易价格需大于0',
                'payment.require' => '请选择支持付款方式',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $payment = json_decode($data['payment'], true);
            if (empty($payment) || count($payment) < 1) {
                $this->result([], 1, '请选择至少一种支付方式');
            }
            $data['num'] = floor($data['num'] * 100) / 100;
            $data['price'] = floor($data['price'] * 100) / 100;
            $user = $this->request->user;
            if ($user['auth'] != 2) {
                $this->result([], 1, '请先进行实名认证');
            }
            if ($user->trade !== md5(md5($data['trade']))) {
                $this->result([], 1, '交易密码错误');
            }
            if ($user['reput'] <= 0) {
                $this->result([], 1, '信誉值太低不能发布交易');
            }
            $hallconfig = (new Config())->where('key_value', 'hallconfig')->value('value');
            $hallconfig = json_decode($hallconfig, true) ?? [];
            $fbmix = $hallconfig['min'] ?? 0;
            $fbmax = $hallconfig['max'] ?? 0;
            $multi = $hallconfig['multi'] ?? 1;
            $minprice = floor($hallconfig['minprice'] * 100) / 10000 ?? 0;
            $maxprice = floor($hallconfig['maxprice'] * 100) / 10000 ?? 0;
            $price = (new Price())->where('date', date('Y-m-d'))->value('price') ?? 0;
            if (empty($price)) {
                $this->result([], 1, '价格获取出错');
            }
            $usdt = (new Config())->where('key_value', 'usdt')->value('value') ?? 6.5;
            $price = $price * $usdt;
            $minmoney = floor($price * 100 * (1 - $minprice)) / 100;
            $maxmoney = floor($price * 100 * (1 + $maxprice)) / 100;
            if ($data['price'] < $minmoney) {
                $this->result([], 1, '求购价格不能低于' . $minmoney);
            }
            if ($data['price'] > $maxmoney) {
                $this->result([], 1, '求购价格不能高于' . $maxmoney);
            }
            $fbcont = (int)$hallconfig['fbcont'] ?? 1;
            $hallcount = (new Halls())->where('user_id', $this->request->user_id)->where(['status' => [0, 1]])->count();
            if ($hallcount >= $fbcont) {
                $this->result([], 1, '发布进行中订单不能超过3条');
            }
            if ($data['num'] < $fbmix || $data['num'] > $fbmax) {
                $this->result([], 1, '发布数量必须在' . $fbmix . '~' . $fbmax . '范围内');
            }
            if ($data['num'] % $multi != 0) {
                $this->result([], 1, '发布数量必须是' . $multi . '的倍数');
            }
            $ordersn = reOrder(new Halls());
            Db::startTrans();
            try {
                $id = (new Halls())->insertGetId([
                    'hall_no' => $ordersn,
                    'user_id' => $this->request->user_id,
                    'type' => 2,
                    'num' => $data['num'],
                    'surplus' => $data['num'],
                    'status' => 0,
                    'price' => $data['price'],
                    'payment' => $data['payment'],
                    'created' => date('Y-m-d H:i:s'),
                ]);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->result([], 1, $exception->getMessage());
            }
            $this->result(['id' => $id, 'hall_no' => $ordersn], 0, '获取成功');
        }
        $this->result([], 1, '发布失败，请重试');
    }

    //取消场外交易
    public function cancel()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require'
            ], [
                'id.require' => '订单ID不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $hall = (new Halls())->where(['user_id' => $this->request->user_id, 'id' => $data['id']])->find();
            if (!$hall) {
                $this->result([], 1, '交易订单不存在');
            }
            if ($hall->status != 0) {
                $this->result([], 1, '该订单状态不可取消');
            }
            Db::startTrans();
            try {
                (new Halls())->where('id', $data['id'])
                    ->where('status', 0)
                    ->update([
                        'status' => 9,
                        'deleted' => date('Y-m-d H:i:s'),
                    ]);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->result($exception->getMessage(), 1, '操作出错，请重试');
            }
            $this->result([], 0, '取消成功');
        }
    }

    //匹配场外交易订单
    public function match()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'number' => 'require|gt|float',
                'price' => 'require|gt',
                'phone' => 'require',
                'trade'  => 'require',
            ], [
                'phone.require' => '对方账号不能为空',
                'number.require' => '交易数量不能为空',
                'number.gt' => '数量必须大于0',
                'number.float' => '数量必须是数字',
                'price.require' => '交易价格不能为空',
                'price.gt' => '价格必须大于0',
                'trade.require' => '交易密码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if ($user->trade !== md5(md5($data['trade']))) {
                $this->result([], 1, '交易密码错误');
            }
            //购买人是否存在
            $buser = (new User())->where('mobile', $data['phone'])->find();
            if (empty($buser)) {
                $this->result([], 1, '接收用户不存在');
            }
            if ($buser['auth'] != 2) {
                $this->result([], 1, '接收用户未实名');
            }
            $starttime = (new Config())->where('key_value', 'starttime')->value('value') ?? '00:00';
            $endtime = (new Config())->where('key_value', 'endtime')->value('value') ?? '24:00';
            if (date('H:i') < $starttime) {
                $this->result([], 1, '交易时间不能低' . $starttime);
            }
            if (date('H:i') > $endtime) {
                $this->result([], 1, '交易时间不能超过' . $endtime);
            }
            if ($user['reput'] <= 0) {
                $this->result([], 1, '信誉值太低不能发布交易');
            }
            if ($user['auth'] != 2) {
                $this->result([], 1, '请先进行实名认证');
            }
            $safety = (new Payment())->where('user_id', $user['id'])->find();
            if (!$safety) {
                $this->result([], 1, '未设置收款方式');
            }
            if ($user->level < 1) {
                $this->result([], 1, 'V1及以下会员无法售卖');
            }
            $handfee = (new UserConfig())->where('level', $user['level'])->value('handfee');
            if (!isset($handfee)) {
                $this->result([], 1, '手续费配置出错');
            }
            $handfee = floor((int)$handfee * 100) / 10000;
            $handfee_num = $data['number'] * $handfee;
            if ($user->tmoney < ($data['number'] + $handfee_num)) {
                $this->result([], 1, '资产数目不足');
            }
            $ordersn = reOrder(new HallTrade());
            $hallTrade = [
                'hall_no' => $ordersn,
                'hall_id' => 0,
                'buyer_id' => $buser['id'],
                'seller_id' => $this->request->user_id,
                'num' => $data['number'],
                'status' => 0,
                'price' => $data['price'],
                'handfee' => $handfee_num,
            ];
            Db::startTrans();
            try {
                $id = (new HallTrade())->insertGetId($hallTrade);
                (new User())->MoneyEdit($user, 3, 5, - ($hallTrade['num'] + $handfee_num), '交易售卖,含手续费' . $handfee_num, $id, $handfee_num, 0);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->result([], 1, $exception->getMessage());
            }
            $this->result(['id' => $id, 'hall_no' => $ordersn], 0, '获取成功');
        }
    }

    //获取交易订单详情
    public function detail()
    {
        $id = $this->request->get('id/d', 0);
        $result = (new HallTrade())->where('id', $id)->field('updated,trade_type,hall_id', true)->find();
        if ($result) {
            $result['buser_mobile'] = (new User())->where('id', $result['buyer_id'])->value('mobile');
            $result['buser_name'] = (new UserAuth())->where('user_id', $result['buyer_id'])->value('name');
            $result['suser_mobile'] = (new User())->where('id', $result['seller_id'])->value('mobile');
            $result['suser_name'] = (new UserAuth())->where('user_id', $result['seller_id'])->value('name');
            $result['payment'] = (new Payment())->field('name,cards,images,type')->where(['user_id' => $result['seller_id']])->select();
            $result['type'] = 0;
            if ($result['buyer_id'] == $this->request->user_id) {
                $result['type'] = 1;
            }
            if ($result['buyer_id'] == $this->request->user_id) {
                $result['type'] = 2;
            }
            $result['status_text'] = config()['config']['halltrade'][$result['status']] ?? "";
        }
        $this->result($result, 0, '获取成功');
    }

    //确认付款交易订单
    public function payment()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'trade_type' => 'require|number',
                'cover' => 'require',
                'trade' => 'require',
            ], [
                'id.require' => '请确认交易订单id',
                'trade_type.require' => '请确认交易方式',
                'cover.require' => '请上传图片',
                'trade.require' => '请输入订单交易密码',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if ($user->trade !== md5(md5($data['trade']))) {
                $this->result([], 1, '交易密码错误');
            }
            $trade = (new HallTrade())->where(['buyer_id' => $this->request->user_id, 'id' => $data['id'], 'status' => 0])->find();
            if (!$trade) {
                $this->result([], 1, '订单不存在或订单当前状态不可付款');
            }
            $res = (new HallTrade())->where(['id' => $trade['id'], 'status' => 0])
                ->update([
                    'trade_type' => $data['trade_type'],
                    'cover' => $data['cover'],
                    'status' => 1,
                    'paytime' => date('Y-m-d H:i:s')
                ]);
            if ($res) {
                $this->result([], 0, '操作成功');
            } else {
                $this->result([], 1, '操作失败，请重试');
            }
        }
    }

    //确认交易完成
    public function finish()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'trade' => 'require',
            ], [
                'id.require' => '请确认交易订单id',
                'trade.require' => '请输入订单交易密码',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if ($user->trade !== md5(md5($data['trade']))) {
                $this->result([], 1, '交易密码错误');
            }
            $trade = (new HallTrade())->where(['seller_id' => $this->request->user_id, 'id' => $data['id'], 'status' => 1])->find();
            if (!$trade) {
                $this->result([], 1, '订单不存在或订单当前状态不可确认');
            }
            // $hall = Halls::where('id', $trade->hall_id)->find();
            // if (!$hall) {
            //     $this->result([], 1, '订单异常，请联系管理员');
            // }
            $buyuser = (new User())->where('id', $trade['buyer_id'])->find();
            Db::startTrans();
            try {
                (new HallTrade())->where('id', $trade['id'])
                    ->where('status', 1)
                    ->update([
                        'status' => 2,
                        'finishtime' => date('Y-m-d H:i:s')
                    ]);
                (new User())->MoneyEdit($buyuser, 3, 6, $trade['num'], '交易购买', $trade['id'], 0, 0);
                Db::commit();
                // $this->checkHall($hall->id);
            } catch (\Exception $exception) {
                Db::rollback();
                $this->result([], 1, $exception->getMessage());
            }
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }


    //取消已匹配场外交易
    public function cancel_match()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'trade' => 'require',
            ], [
                'id.require' => '请确认交易订单id',
                'trade.require' => '请输入订单交易密码',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = $this->request->user;
            if ($user->trade !== md5(md5($data['trade']))) {
                $this->result([], 1, '交易密码错误');
            }
            $trade = (new HallTrade())->where(['buyer_id' => $this->request->user_id, 'status' => [0, 1], 'id' => $data['id']])->find();
            if (!$trade) {
                $this->result([], 1, '交易订单不存在或状态不可取消');
            }
            // $hall = (new Halls())->where('id', $trade->hall_id)->find();
            $selluser = (new User())->where('id', $trade['seller_id'])->find();
            Db::startTrans();
            try {
                (new User())->where('id', $trade['buyer_id'])->setDec('reput', 1);
                (new HallTrade())->where('id', $data['id'])
                    ->where(['status' => [0, 1]])
                    ->update([
                        'status' => 10, 'caceltime' => date('Y-m-d H:i:s')
                    ]);
                (new User())->MoneyEdit($selluser, 3, 7, ($trade['num'] + $trade['handfee']), '交易售卖' . $trade['num'] . '取消', $trade['id'], $trade['handfee'], 0);
                Db::commit();
                // $this->checkHall($trade->hall_id);
            } catch (\Exception $exception) {
                Db::rollback();
                $this->result([], 1, $exception->getMessage());
            }
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败，请重试');
    }

    //交易申诉
    public function appeal()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'reason' => 'require',
            ], [
                'id.require' => 'ID不能为空',
                'reason.require' => '请输入原由',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['images'])) {
                $images = json_decode($data['images'], true);
                if (empty($images) || count($images) <= 0) {
                    $this->result([], 1, '图片格式错误');
                }
            }
            $trade = (new HallTrade())->where(['id' => $data['id']])->find();
            if (!$trade) {
                $this->result([], 1, '交易订单不存在');
            }
            if ($trade->status != 0 && $trade->status != 1) {
                $this->result([], 1, '交易订单不可申诉');
            }
            if ($trade->seller_id == $this->request->user_id) {
                $status = [
                    'status' => 9,
                ];
                $type = 2;
            } else if ($trade->buyer_id == $this->request->user_id) {
                $status = [
                    'status' => 8,
                ];
                $type = 1;
            } else {
                $this->result([], 1, '非买卖方不可申诉此订单');
            }
            $appeal = [
                'trade_id' => $trade->id,
                'user_id' => $this->request->user_id,
                'type' => $type,
                'proof' => $data['images'],
                'reason' => $data['reason'],
                'created' => date('Y-m-d H:i:s'),
            ];
            Db::startTrans();
            try {
                (new HallTrade())->where('id', $data['id'])
                    ->update($status);
                (new HallTradeAppeal())->insert($appeal);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                $this->result([], 1, $exception->getMessage());
            }
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }


    // protected function checkHall($id)
    // {
    //     $hall = (new Halls())->where('id', $id)->find();
    //     $results = (new HallTrade())
    //         ->where('hall_id', $id)
    //         ->where('status', 'in', '0,1,8,9')
    //         ->field('id')
    //         ->select();
    //     if (count($results) > 0 && $hall['status'] == 1 && $hall['surplus'] > 0) {
    //         if ($hall['type'] == 2) {
    //             (new Halls())->where('id', $id)->update([
    //                 'status' => 9,
    //                 'deleted' => date('Y-m-d H:i:s'),
    //             ]);
    //         } else {
    //             (new Halls())->where('id', $id)->update(['status' => 0]);
    //         }
    //     }
    //     if (count($results) <= 0 && $hall['surplus'] == 0) {
    //         (new Halls())->where('id', $id)->update(['status' => 2]);
    //     }
    //     return true;
    // }

    public function hall()
    {
        $status = $this->request->get('status/d', 0);
        $result = (new Halls())->where('user_id', $this->request->user_id)
            ->field('id,hall_no,num,user_id,price,surplus,status,created')
            ->order('id desc');
        if ($status == 1) {
            $result = $result->where(['status' => [0, 1]]);
        }
        if ($status == 2) {
            $result = $result->where(['status' => [2, 9]]);
        }
        $result = $result->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['status_text'] = config()['config']['hall'][$results['status']] ?? "";
        }
        $this->result($result, 0, '获取成功');
    }

    public function halltrade()
    {
        $status = $this->request->get('status/d', 0);
        $type = $this->request->get('type/d', 0);
        if (empty($type)) {
            $this->result([], 1, '类型参数必须上传');
        }
        $result = (new HallTrade())->field('id,hall_no,num,price,handfee,status,created')
            ->order('id desc');
        if ($status == 1) {
            $result = $result->where(['status' => [0, 1, 8, 9]]);
        }
        if ($status == 2) {
            $result = $result->where(['status' => [2, 10]]);
        }
        if ($type == 1) {
            $result = $result->where(['buyer_id' => $this->request->user_id]);
        }
        if ($type == 2) {
            $result = $result->where(['seller_id' => $this->request->user_id]);
        }
        $result = $result->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($result as $results) {
            $results['status_text'] = config()['config']['halltrade'][$results['status']] ?? "";
        }
        $this->result($result, 0, '获取成功');
    }
}
